package com.haoxuer.discover.plug.aliyun;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.haoxuer.discover.plug.api.ProxyPlugin;
import com.haoxuer.discover.plug.api.SendCodePlugin;
import com.haoxuer.discover.plug.data.entity.PluginConfig;
import com.haoxuer.discover.rest.base.ResponseObject;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component("aliSmsPlugin")
public class AliSmsPlugin extends SendCodePlugin {

  @Override
  public ResponseObject sendCode(Map<String, String> params) {
    ResponseObject result=new ResponseObject();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String code = params.get("code");
      String template = params.get("template");
      String phone = params.get("phone");
      String appkey = pluginConfig.getAttribute("appkey");
      String secret = pluginConfig.getAttribute("secret");
      String tempSignName = pluginConfig.getAttribute("signName");
      String templateTemp = pluginConfig.getAttribute(template);

      DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", appkey, secret);
      IAcsClient client = new DefaultAcsClient(profile);

      CommonRequest request = new CommonRequest();
      //request.setProtocol(ProtocolType.HTTPS);
      request.setMethod(MethodType.POST);
      request.setDomain("dysmsapi.aliyuncs.com");
      request.setVersion("2017-05-25");
      request.setAction("SendSms");
      request.putQueryParameter("RegionId", "cn-hangzhou");
      request.putQueryParameter("PhoneNumbers", phone);
      request.putQueryParameter("SignName", tempSignName);
      request.putQueryParameter("TemplateCode", templateTemp);
      JSONObject object=new JSONObject();
      object.put("code",""+code);
      request.putQueryParameter("TemplateParam", object.toString());
      try {
        CommonResponse response = client.getCommonResponse(request);
      } catch (ServerException e) {
        result.setCode(501);
        result.setMsg(e.getErrMsg());
      } catch (ClientException e) {
        result.setCode(502);
        result.setMsg(e.getErrMsg());
      }
    }
    return result;
  }


  @Override
  public String getName() {
    return "ada.young";
  }

  @Override
  public String getVersion() {
    return "";
  }

  @Override
  public String viewName() {
    return "aliyun";
  }

}
